<template>
  <div>
    <el-menu :default-active="tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="my" v-if="myTargetAdministration">我的</el-menu-item>
      <el-menu-item index="group" v-if="groupTargetAdministration">事业部</el-menu-item>
      <el-menu-item index="department" v-if="departmentTargetAdministration">部门</el-menu-item>
      <el-menu-item index="all" v-if="allTargetAdministration">全部</el-menu-item>
    </el-menu>
    <el-tabs v-model="activeName" style="margin-top:20px;" type="card" @tab-click="changeActiveName">
      <el-tab-pane label="日目标" name="first">
        <div style="margin-top: 20px">
          <!--搜索-->
          <el-form :inline="true" :model="listQuery" size="mini" label-width="80px">
            <el-form-item label="日期：">
              <el-date-picker
                v-model="listQuery.targetDate"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="业务员：" v-if="tab!='my'">
              <el-cascader
                size="mini"
                collapse-tags
                :show-all-levels="false"
                v-model="listQuery.userId"
                placeholder="请选择部门/事业部/人员"
                :options="userList"
                :props="props"></el-cascader>
            </el-form-item>
            <el-form-item label="状态：">
              <el-select v-model="listQuery.isFinished"  placeholder="请选择" clearable>
                <el-option key="1" label="已完成" value="1"></el-option>
                <el-option key="0" label="未完成" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                @click="handleSearchList()"
                type="primary">
                查询
              </el-button>
              <el-button
                :loading="downLoading1"
                v-if="tab == 'all' || tab == 'department'"
                @click="downloadExcel(1)"
                type="primary">
                导出
              </el-button>
              <el-button
                v-if="tab == 'my'"
                @click="showPop('add','')"
                type="primary">
                设置目标
              </el-button><!--v-if="tab == 'my'"-->
              <el-button
                :loading="btnLoading3"
                @click="sync"
                type="primary">
                更新当日销量
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <!--数据列表-->
        <div class="table-container">
          <div id="myChart" :style="{'height':'300px'}" v-loading="loadingChart"></div>
          <div style="font-size:14px;padding:20px 0">合计目标销量：<span style="font-weight: bold">{{ saleTargetAllNum }}</span>吨<span style="padding-left:20px;">实际销量：<span style="font-weight: bold">{{ saleActualAllNum }}</span>吨</span><span style="padding-left:20px">完成率：<span style="font-weight: bold">{{ finishedRate }}</span></span></div>
          <el-table
            v-loading="listLoading"
            :data="tableData"
            border
            style="width: 100%; margin-top: 20px">
            <el-table-column
              label="日期"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.targetDate}}
              </template>
            </el-table-column>
            <el-table-column
              label="业务员"
              min-width="150"
              align="center">
              <template slot-scope="scope">
                {{scope.row.userRealName}}
              </template>
            </el-table-column>
            <el-table-column
              label="目标销量(吨)"
              min-width="150"
              align="center">
              <template slot-scope="scope">
                {{scope.row.saleTargetAllNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="新客户录入"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.customerTargetNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="沟通数"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.contactTargetNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="电话数"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.mobileTargetNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="拜访数"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.visitTargetNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="跟进目标"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.trackingTargetNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="实际完成量(吨)"
              min-width="150"
              align="center">
              <template slot-scope="scope">
                {{scope.row.saleActualAllNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="实际新客户录入"
              min-width="130"
              align="center">
              <template slot-scope="scope">
                {{scope.row.customerActualNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="实际沟通"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.contactActualNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="实际电话数"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.mobileActualNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="实际拜访数"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.visitActualNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="实际跟进"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.trackingActualNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="匹配跟进数"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.todayHasTrackingNum}}
              </template>
            </el-table-column>
            <el-table-column
              label="匹配程度"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.todayHasTracking }}
              </template>
            </el-table-column>
            <el-table-column
              label="状态"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{scope.row.targetState}}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="showPop2(scope.row)" v-if="tab=='my' && !scope.row.targetCheckTime && scope.row.targetDateTime <= nowdate0">确认</el-button>
                <el-button type="text" @click="showPop3(scope.row)" v-if="tab != 'group'">明细</el-button>
                <el-button type="text" v-if="scope.row.targetDateTime > nowDate && tab=='my'" @click="showPop('edit',scope.row)">修改</el-button><!--只限当天以后-->
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes,prev, pager, next,jumper"
            :current-page.sync="listQuery.pageNum"
            :page-size="listQuery.pageSize"
            :page-sizes="[10,15,20]"
            :total="count">
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="日目标明细" name="second" v-if="tab != 'group'">
        <div style="margin-top: 20px">
          <!--搜索-->
          <el-form :inline="true" :model="listQuery2" size="mini" label-width="80px">
            <el-form-item label="日期：">
              <el-date-picker
                v-model="listQuery2.targetDate"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="业务员：" v-if="tab!='my'">
              <el-cascader
                size="mini"
                collapse-tags
                :show-all-levels="false"
                v-model="listQuery2.userId"
                placeholder="请选择部门/事业部/人员"
                :options="userList"
                :props="props"></el-cascader>


            </el-form-item>
            <el-form-item label="状态：">
              <el-select v-model="listQuery2.isFinished"  placeholder="请选择" clearable>
                <el-option key="1" label="已完成" value="1"></el-option>
                <el-option key="0" label="未完成" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="品类：">
              <el-select
                filterable
                clearable
                v-model="listQuery2.goodsName">
                <el-option
                  v-for="item in options2"
                  :key="item.goodsName"
                  :label="item.goodsName"
                  :value="item.goodsName">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="牌号：">
              <el-select v-model="listQuery2.goodsKingId" filterable placeholder="请选择" clearable>
                <el-option
                  v-for="item in goodsList"
                  :key="item.kingId"
                  :label="item.goodsSn"
                  :value="item.kingId">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                @click="handleSearchList2()"
                type="primary">
                查询
              </el-button>
              <el-button
                :loading="downLoading2"
                v-if="tab == 'all' || tab == 'department'"
                @click="downloadExcel(2)"
                type="primary">
                导出
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <!--数据列表-->
        <div class="table-container">
          <el-table
            v-loading="listLoading2"
            :data="tableData2"
            :span-method="objectSpanMethod"
            border
            style="width: 100%; margin-top: 20px">
            <el-table-column
              label="日期"
              min-width="100"
              prop="targetDate"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.targetDate}}
              </template>
            </el-table-column>
            <el-table-column
              label="员工姓名"
              min-width="100"
              prop="userRealName"
              align="center">
              <template slot-scope="scope" >
                {{ scope.row.userRealName}}
              </template>
            </el-table-column>
            <el-table-column label="部门" align="center"  min-width="100" prop="departmentName">
              <template slot-scope="scope" >
                {{ scope.row.departmentName}}
              </template>
            </el-table-column>
            <el-table-column
              label="品类"
              prop="goodsSn"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.goodsName}}
              </template>
            </el-table-column>
            <el-table-column
              label="产品牌号"
              prop="goodsSn"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.goodsSn}}
              </template>
            </el-table-column>
            <el-table-column
              prop="saleTargetNum"
              label="预计销量(吨)"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.saleTargetNum}}
              </template>
            </el-table-column>
            <el-table-column
              prop="saleActualNum"
              label="实际销量(吨)"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.saleActualNum}}
              </template>
            </el-table-column>
            <el-table-column
              prop="targetState"
              label="状态"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.targetState}}
              </template>
            </el-table-column>
            <el-table-column
              prop="customerName"
              label="客户名称"
              min-width="150"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.customerName}}
              </template>
            </el-table-column>
            <el-table-column
              prop="inquiryCount"
              label="询盘次数"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.inquiryCount}}
              </template>
            </el-table-column>
            <el-table-column
              prop="customerName"
              label="客户销量(吨)"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.customerSaleActuaNum}}
              </template>
            </el-table-column>
            <el-table-column
              prop="orderSn"
              label="关联订单"
              min-width="200"
              align="center">
              <template slot-scope="scope">
                <span v-for="item in scope.row.orderList" :key="item.orderId" style="padding-left:5px">{{item.orderSn}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="checkContent"
              label="销售复盘"
              min-width="200"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.checkContent}}
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              background
              @size-change="handleSizeChange2"
              @current-change="handleCurrentChange2"
              layout="total, sizes,prev, pager, next,jumper"
              :current-page.sync="listQuery2.pageNum"
              :page-size="listQuery2.pageSize"
              :page-sizes="[10,15,20]"
              :total="count2">
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!--设置目标-->
    <el-dialog
      :close-on-click-modal="false"
      title="设置目标"
      :visible.sync="dialogVisible"
      width="800px">
      <el-form :model="form" size="mini" label-width="100px" ref="form" :rules="rules">

        <el-row>
          <el-col :span="8">
            <el-form-item label="日期：" prop="targetDate">
              <el-date-picker
                @change="changeTargetDate"
                style="width:150px"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
                v-model="form.targetDate"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="新录入客户：" prop="customerTargetNum">
              <el-input v-model="form.customerTargetNum" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="crm跟进数：" prop="trackingTargetNum">
              <el-input v-model="form.trackingTargetNum" type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div style="display: flex;">
          <el-form-item label="总沟通数量：" prop="contactTargetNum">
            <el-input-number v-model="form.contactTargetNum" :min="0" style="width:100px" controls-position="right" :precision="0"></el-input-number>
          </el-form-item>
          <el-form-item label="电话数量：" label-width="84px" prop="mobileTargetNum">
            <el-input-number v-model="form.mobileTargetNum" :min="0" :max="form.contactTargetNum - form.visitTargetNum" :precision="0" style="width:100px" controls-position="right" ></el-input-number>
          </el-form-item>
          <el-form-item label="拜访数量：" label-width="84px" prop="visitTargetNum">
            <el-input-number v-model="form.visitTargetNum" :min="0" :max="form.contactTargetNum - form.mobileTargetNum" :precision="0" style="width:100px" controls-position="right"></el-input-number>
          </el-form-item>
          <el-form-item  label-width="74px" label="其它：">{{form.contactTargetNum - form.mobileTargetNum - form.visitTargetNum}}</el-form-item>
        </div>

        <el-form-item label="销售目标：">
          <el-button @click="addGoodsItem">添加目标</el-button>
        </el-form-item>
        <el-table ref="targetTable" :data="form.detailData" style="width:100%;margin-top: 20px" border>
          <el-table-column label="产品牌号"  min-width="150" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px" :prop="`detailData.${scope.$index}.goodsKingId`" :rules="rules.goodsKingId">
                <el-select v-model="scope.row.goodsKingId" filterable placeholder="请选择" clearable @change="changeGoodsSn(scope.$index,scope.row.goodsKingId)">
                  <el-option
                    v-for="item in goodsList"
                    :key="item.kingId"
                    :label="item.goodsSn"
                    :value="item.kingId">
                  </el-option>
                </el-select>
                <div style="line-height: 18px;text-align: left;">
                  <span
                    :style="{color:item.urgencyType == '紧急' ? 'red':'#000'}"
                    v-for="(item,index) in scope.row.goodsSnTypeList" :key="index">
                    {{item.urgencyType}}{{item.goodsNum}}吨({{item.isFullCar}})
                    <span v-if="index < scope.row.goodsSnTypeList.length-1">/</span>
                  </span>
                </div>
              </el-form-item>
              <div>

              </div>
            </template>
          </el-table-column>
          <el-table-column label="客户名称"  min-width="200" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px" :prop="`detailData.${scope.$index}.customerIds`" :rules="rules.customerIds">
                <el-select
                  style="width:100%;"
                  multiple
                  clearable
                  v-model="scope.row.customerIds"
                  filterable
                  remote
                  value-key="customerId"
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="remoteMethod"
                  :loading="loading">
                  <el-option v-for="item in customerList" :key="item.customerId" :label="item.customerName" :value="item.customerId">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="预计销量(吨)"  min-width="100" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0px" :prop="`detailData.${scope.$index}.saleTargetNum`" :rules="rules.saleTargetNum">
                <el-input v-model="scope.row.saleTargetNum"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作"  min-width="100" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="delItem(scope.$index)" v-if="scope.$index > 0">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>

    <!--确认目标-->
    <el-dialog
      :close-on-click-modal="false"
      title="确认目标"
      :visible.sync="dialogVisible2"
      width="900px">
      <el-form :model="form2" size="mini" label-width="160px" ref="form2" :rules="rules2">
          <el-row>
            <el-col :span="8">
              <el-form-item label="日期：" prop="targetDate" style="margin-bottom: 5px">
                    {{form2.targetDate}}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="目标总沟通数量："  style="margin-bottom: 5px">
                {{form2.contactTargetNum}}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际总沟通数量：" prop="contactActualNum" >
                <el-input-number v-model="form2.contactActualNum" :min="0" style="width:100px" controls-position="right" :precision="0"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="新录入客户(目标/实际)：" style="margin-bottom: 5px">
                {{form2.customerTargetNum}} / <span style="font-weight: bold">{{form2.customerActualNum}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="目标电话数量："   style="margin-bottom: 5px">
                {{form2.mobileTargetNum}}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际电话数量："  prop="mobileActualNum" >
                <el-input-number v-model="form2.mobileActualNum" :min="0" :max="form2.contactActualNum - form2.visitActualNum" :precision="0" style="width:100px" controls-position="right"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="跟进客户(目标/实际)：" style="margin-bottom: 5px">
                {{form2.trackingTargetNum}} / <span style="font-weight: bold">{{form2.trackingActualNum}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="目标拜访数量："  style="margin-bottom: 5px">
                {{form2.visitTargetNum}}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际拜访数量：" prop="visitActualNum">
                <el-input-number v-model="form2.visitActualNum" :min="0" :max="form2.contactActualNum - form2.mobileActualNum" :precision="0" style="width:100px" controls-position="right"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="8">
              <el-form-item   label="目标其它：" style="margin-bottom: 5px">
                {{form2.contactTargetNum - form2.mobileTargetNum - form2.visitTargetNum}}
              </el-form-item>
            </el-col>
             <el-col :span="8">
               <el-form-item  label="实际其它：">
                 {{form2.contactActualNum - form2.mobileActualNum - form2.visitActualNum}}
               </el-form-item>
             </el-col>
          </el-row>
          <el-table ref="targetTable" :data="form2.detailData" style="width:100%;margin-top: 20px" border :span-method="objectSpanMethod">
            <el-table-column
              label="产品牌号"
              prop="goodsSn"
              min-width="200"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.goodsSn}}
              </template>
            </el-table-column>
            <el-table-column
              prop="saleTargetNum"
              label="预计销量(吨)"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.saleTargetNum}}
              </template>
            </el-table-column>
            <el-table-column
              prop="saleActualNum"
              label="实际销量(吨)"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.saleActualNum}}
              </template>
            </el-table-column>
            <el-table-column
              prop="targetState"
              label="状态"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.targetState}}
              </template>
            </el-table-column>
            <el-table-column
              prop="customerName"
              label="客户名称"
              min-width="200"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.customerName}}
              </template>
            </el-table-column>
            <el-table-column
              prop="customerName"
              label="客户销量"
              min-width="100"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.customerSaleActuaNum}}
              </template>
            </el-table-column>
            <el-table-column
              prop="orderSn"
              label="关联订单"
              min-width="200"
              align="center">
              <template slot-scope="scope">
                <span v-for="item in scope.row.orderList" :key="item.orderId" style="padding-left:5px">{{item.orderSn}}</span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              prop="checkContent"
              label="销售复盘"
              min-width="200"
              align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.trackingId" style="text-align: left">
                   {{scope.row.trackingContent}}
                  <div style="text-align: right">
                    <el-button type="primary" plain @click="scope.row.trackingId = 0" size="mini" round>更新</el-button>
                  </div>

                </div>
                 <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" :rows="2" v-model="scope.row.checkContent" v-else></el-input>
              </template>
            </el-table-column>

          </el-table>
        </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>

    <!--目标明细-->
    <el-dialog
      :close-on-click-modal="false"
      title="目标明细"
      :visible.sync="dialogVisible3"
      width="800px">
      <el-table
        v-loading="listLoading3"
        :data="tableData3"
        :span-method="objectSpanMethod"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column
          label="日期"
          min-width="100"
          prop="targetDate"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.targetDate}}
          </template>
        </el-table-column>
        <el-table-column
          label="员工姓名"
          min-width="100"
          prop="userRealName"
          align="center">
          <template slot-scope="scope" >
            {{ scope.row.userRealName}}
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center"  min-width="100" prop="departmentName">
          <template slot-scope="scope" >
            {{ scope.row.departmentName}}
          </template>
        </el-table-column>
        <el-table-column
          label="品类"
          prop="goodsSn"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.goodsName}}
          </template>
        </el-table-column>
        <el-table-column
          label="产品牌号"
          prop="goodsSn"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.goodsSn}}
          </template>
        </el-table-column>
        <el-table-column
          prop="saleTargetNum"
          label="预计销量(吨)"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.saleTargetNum}}
          </template>
        </el-table-column>
        <el-table-column
          prop="saleActualNum"
          label="实际销量(吨)"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.saleActualNum}}
          </template>
        </el-table-column>
        <el-table-column
          prop="targetState"
          label="状态"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.targetState}}
          </template>
        </el-table-column>
        <el-table-column
          prop="customerName"
          label="客户名称"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.customerName}}
          </template>
        </el-table-column>
        <el-table-column
          prop="inquiryCount"
          label="询盘次数"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.inquiryCount}}
          </template>
        </el-table-column>
        <el-table-column
          prop="customerName"
          label="客户销量(吨)"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.customerSaleActuaNum}}
          </template>
        </el-table-column>
        <el-table-column
          prop="orderSn"
          label="关联订单"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            <span v-for="item in scope.row.orderList" :key="item.orderId" style="padding-left:5px">{{item.orderSn}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="checkContent"
          label="销售复盘"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.checkContent}}
          </template>
        </el-table-column>
      </el-table>
      <div style="overflow: hidden">
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange3"
            @current-change="handleCurrentChange3"
            layout="total, sizes,prev, pager, next,jumper"
            :current-page.sync="listQuery3.pageNum"
            :page-size="listQuery3.pageSize"
            :page-sizes="[10,15,20]"
            :total="count3">
          </el-pagination>
        </div>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import {getCustomerOption,saleTargetTargetList,orderGoodsList,getGoodsClassList,getOrderUsersList} from '@/api/partner'
import { saleTargetList,saleTargetDetailList,saleTargetDetail,saleTargetSet,saleTargetCheck,saleTargetAnalysis,syncSaleActualNum,purchaseTargetData} from '@/api/allInLine/goods.js'
import {goodsList} from '@/api/company'
import {saleUserList} from '@/api/data.js'
import {formatDate} from '@/utils/date';
import store from '@/store'
import { mapGetters } from 'vuex'
const defaultListQuery={
  "tab" : "", //所有-tab,我的-my,师徒-share,部门-department
  "userId" : [],  //业务员ID
  "isFinished" : "", //是否已完成(是-1，否-0)
  "targetDate" : [], //目标日期
  "isExport" : 0, //是否导出(1是，0否)
  "pageNum" : 1,
  "pageSize" : 10
};

const defaultListQuery2={
  "targetId" : '', //目标ID
  "tab" : "", //所有-tab,我的-my,师徒-share,部门-department
  "userId" : [],  //业务员ID
  "isFinished" : "", //是否已完成(是-1，否-0)
  "targetDate" : [], //目标日期
  goodsKingId:'',
  goodsName:'',
  "isExport" : 0, //是否导出(1是，0否)
  "pageNum" : 1,
  "pageSize" : 10
};
const defaultForm={
  "targetId" : 0,
  "targetDate" : "",
  "customerTargetNum" : '', // #新录入客户目标数量
  "trackingTargetNum" : '', // #跟进客户目标数量
  "contactTargetNum" :'', // #沟通数量
  "mobileTargetNum" : '',// #电话数量
  "visitTargetNum" : '', //#拜访目标数量
  "detailData" :  []
}

const defaultForm2={
  customerTargetNum : '',
  customerActualNum :'',
  contactTargetNum :'',
  contactActualNum :'',
  trackingTargetNum :'',
  trackingActualNum :'',
  mobileTargetNum :'',
  mobileActualNum :'',
  visitTargetNum :'',
  visitActualNum :'',
  targetId:'',
  targetDate:'',
  detailData:[],
}

const defaultItme = {
  "detailId" : 0,  //明细ID，为0时表示新增，否则编辑
  "customerIds" :[], //客户ID
  "goodsKingId" : '', //产品SAPID
  "saleTargetNum" : '', //预计销量
  goodsSnTypeList:[]
}
export default {
  name: "sourceGoodsSetting",
  data(){
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData: [],
      listLoading: false,
      roles:store.getters.roles ? store.getters.roles : [],
      loading:false,
      count:0,
      activeName:'first',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },

      listQuery2: JSON.parse(JSON.stringify(defaultListQuery2)),
      tableData2: [{},{}],
      listLoading2: false,
      count2:0,

      userOptionList:[],
      tab:'',
      dialogVisible:false,
      form:JSON.parse(JSON.stringify(defaultForm)),
      btnLoading:false,
      goodsList:[],
      customerList:[],
      rules:{
        customerTargetNum:[{required: true, message: '此项必填', trigger: 'blur'},],
        contactTargetNum:[{required: true, message: '此项必填', trigger: 'blur'},],
        targetDate:[{required: true, message: '此项必填', trigger: 'change'},],
        customerIds:[{required: true, message: '此项必填', trigger: 'change'},],
        goodsKingId:[{required: true, message: '此项必填', trigger: 'change'},],
        saleTargetNum:[{required: true, message: '此项必填', trigger: 'blur'},],
        mobileTargetNum:[{required: true, message: '此项必填', trigger: 'blur'},],
        visitTargetNum:[{required: true, message: '此项必填', trigger: 'blur'},],
        trackingTargetNum:[{required: true, message: '此项必填', trigger: 'blur'},],
      },
      dialogVisible2:false,
      form2:JSON.parse(JSON.stringify(defaultForm2)),
      btnLoading2:false,
      rules2:{
        contactActualNum:[{required: true, message: '此项必填', trigger: 'blur'},],
        mobileActualNum:[{required: true, message: '此项必填', trigger: 'blur'},],
        visitActualNum:[{required: true, message: '此项必填', trigger: 'blur'},],
      },

      dialogVisible3:false,
      tableData3: [],
      count3:0,
      listLoading3: false,
      listQuery3: JSON.parse(JSON.stringify(defaultListQuery2)),

      downLoading1:false,
      downLoading2:false,
      btnLoading3:false,

      saleTargetAllNum:'',
      saleActualAllNum:'',
      finishedRate:'',
      loadingChart:false,
      nowdate0:'',
      options2:[],
      props:{multiple: true,label:'value',value:'label',emitPath:false},
      userList:[],
      popType:''

    }
  },
  props: {

    nowDate:{
      type: Number,
      default: () => parseInt(Date.parse(new Date())/1000)
    },
    startDate:{
      type: String,
      default: () => ''
    },
    endDate:{
      type: String,
      default: () => ''
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId',
      'isMange',
    ]),
    myTargetAdministration(){
      if(this.roles.indexOf("myTargetAdministration") != -1){
        return true
      }else{
        return false
      }
    },
    departmentTargetAdministration(){
      if(this.roles.indexOf("departmentTargetAdministration") != -1){
        return true
      }else{
        return false
      }
    },
    allTargetAdministration(){
      if(this.roles.indexOf("allTargetAdministration") != -1){
        return true
      }else{
        return false
      }
    },
    groupTargetAdministration(){
      if(this.roles.indexOf("groupTargetAdministration") != -1){
        return true
      }else{
        return false
      }
    },
  },
  created() {

    this.listQuery.targetDate = [this.startDate,this.endDate];
    if(this.myTargetAdministration){
      this.tab = 'my'
    }else if(this.groupTargetAdministration){
      this.tab = 'group'
    }else if(this.departmentTargetAdministration){
      this.tab = 'department'
    }else if(this.allTargetAdministration){
      this.tab = 'all'
    }
    this.getList();
    this.getChartsData();
    orderGoodsList().then((res)=>{
      this.goodsList = res.list
    })
    let  date = new Date(); // 获取当前时间
    date.setHours(0, 0, 0, 0); // 将时、分、秒和毫秒设为 0
    this.nowdate0 = parseInt(date.getTime()/1000);
    this.remoteMethod3()

    saleUserList().then((res)=>{
      this.userList = res
    })

  },
  filters: {



  },
  methods:{
    //获取品类列表
    remoteMethod3() {
      getGoodsClassList().then((res)=>{
        this.options2 = res;
      }).catch(()=>{
      });
    },
    changeTargetDate(){
      this.form.detailData.forEach((el,index)=>{
        this.changeGoodsSn(index,el.goodsKingId)
      })
    },
    changeGoodsSn(index,goodsKingId){
      console.log("index",index)
      this.$set(this.form.detailData[index],'goodsSnTypeList',[])
      if(this.form.targetDate && goodsKingId){
        purchaseTargetData({targetDate:this.form.targetDate,goodsKingId:goodsKingId}).then((res)=>{
          this.$set(this.form.detailData[index],'goodsSnTypeList',res)
        })
      }


    },
    changeActiveName(){
      this.listQuery.targetDate = [this.startDate,this.endDate];
      this.listQuery2.targetDate = [this.startDate,this.endDate];
      if(this.activeName == 'first'){
        this.handleSearchList()
      }else{
        this.handleSearchList2()
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }){
      let rowList = ['targetDate','userRealName','departmentName','goodsSn','saleTargetNum','saleActualNum','targetState']
      if(rowList.indexOf(column.property) != -1){
        if (row.isRowSpan) {
          return {
            rowspan: row.rowNum,
            colspan: 1
          };
        }else{
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }else{
        return {
          rowspan: 1,
          colspan: 1
        }
      }

    },
    getChartsData(){
      this.loadingChart = true
      saleTargetAnalysis({tab:this.tab,userId:this.listQuery.userId,isFinished:this.listQuery.isFinished,targetDate:this.listQuery.targetDate}).then((res)=>{
        this.$nextTick(()=>{
          this.drawCaiGouCount(res.dateList,res.saleTargetList,res.saleActualList)
        })
      })
    },
    //画图表
    drawCaiGouCount(x,y1,y2){
      let myChart = this.$echarts.init(document.getElementById('myChart'));
      // 绘制图表
      myChart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['目标销量', '实际销量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: x
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '目标销量',
            type: 'line',
            data: y1,
            smooth: true
          },
          {
            name: '实际销量',
            type: 'line',
            data: y2,
            smooth: true
          },
        ]
      });
      this.loadingChart = false;
    },

    sync(){
      this.btnLoading3 = true;
      syncSaleActualNum({tab:this.tab,userId:this.listQuery.userId,isFinished:this.listQuery.isFinished,targetDate:this.listQuery.targetDate}).then(()=>{
        this.btnLoading3 = false;
        this.$message({message: '更新成功', type: 'success'});
      }).catch(()=>{
        this.btnLoading3 = false;
      })
    },
    //下载excle
    downloadExcel(type){
      let data,fn
      if(type == 1){
        data = JSON.parse(JSON.stringify(this.listQuery));
        fn = saleTargetList;
        this.downLoading1 = true;
      }else{
        data = JSON.parse(JSON.stringify(this.listQuery2));
        fn = saleTargetDetailList;
        this.downLoading2 = true;
      }
      data.isExport = 1;
      data.tab = this.tab;
      fn(data).then((res)=>{
        this.downLoading1 = false;
        this.downLoading2 = false;
        require.ensure([], () => {
          const { export_json_to_excel } = require('sheet/Export2Excel');
          const tHeader = res.title;
          const filterVal = res.columns;
          const list = res.list;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, res.fileName);
        })
      })
    },

    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    showPop(type,item){
      this.dialogVisible = true;
      this.form = JSON.parse(JSON.stringify(defaultForm));
      var today = new Date();  // 获取当前日期
      var tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
      this.form.targetDate = formatDate(tomorrow, 'yyyy-MM-dd');
      this.popType = type
      if(type == 'edit'){
        saleTargetDetail({targetId:item.targetId}).then((res)=>{
          this.form.targetId = res.targetId;
          this.form.customerTargetNum = res.customerTargetNum
          this.form.contactTargetNum = res.contactTargetNum
          this.form.trackingTargetNum = res.trackingTargetNum
          this.form.mobileTargetNum = res.mobileTargetNum
          this.form.visitTargetNum = res.visitTargetNum;
          this.form.targetDate = res.targetDate;
          this.customerList = [];
          res.detailList.forEach((el)=>{
            let customerIds = []
            el.customerList.forEach((item)=>{
              customerIds.push(parseInt(item.customerId))
              this.customerList.push({
                customerId:parseInt(item.customerId),
                customerName:item.customerName,
              })
            })
            this.form.detailData.push({
              detailId : el.detailId,
              customerIds : customerIds,
              goodsKingId : el.goodsKingId,
              saleTargetNum : el.saleTargetNum,
              goodsSnTypeList:[]
            })

          })
          this.changeTargetDate()
        })
      }else{
        this.form.detailData.push(JSON.parse(JSON.stringify(defaultItme)))
      }
    },

    delItem(index){
      this.form.detailData.splice(index,1)
    },
    addGoodsItem(){
      this.form.detailData.push(JSON.parse(JSON.stringify(defaultItme)))
    },
    //关闭目标设置
    handleClose(){
      this.dialogVisible = false;
    },
    handleConfirm(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let data = JSON.parse(JSON.stringify(this.form));
          data.detailData.forEach((el)=>{
            el.customerIds = el.customerIds.join(",")
          })
          saleTargetSet(data).then((res)=>{
            this.btnLoading = false;
            this.handleClose();
            this.getList();
            this.getChartsData()
          }).catch(()=>{
            this.btnLoading = false;
          })
        }
      })
    },

    //显示确认目标
    showPop2(item){
      this.dialogVisible2 = true;
      this.form2 = JSON.parse(JSON.stringify(defaultForm2));
      saleTargetDetail({targetId:item.targetId}).then((res)=>{
        this.form2.targetId = res.targetId;
        this.form2.targetDate = res.targetDate;
        this.form2.saleTargetAllNum = res.saleTargetAllNum;
        this.form2.saleActualAllNum = res.saleActualAllNum;

        this.form2.customerTargetNum = res.customerTargetNum;
        this.form2.customerActualNum = res.customerActualNum;

        this.form2.trackingTargetNum = res.trackingTargetNum
        this.form2.trackingActualNum = res.trackingActualNum

        this.form2.contactTargetNum = res.contactTargetNum;
        this.form2.contactActualNum = '';

        this.form2.mobileTargetNum = res.mobileTargetNum
        this.form2.mobileActualNum = ''

        this.form.visitTargetNum = res.visitTargetNum
        this.form2.visitActualNum = ''

        let list = this.farmtList(res.detailList)
        this.form2.detailData = list
        console.log(this.form2)
      })


    },

    handleConfirm2(){
      this.$refs.form2.validate((valid) => {
        if (valid) {
          this.btnLoading2 = true;
          let data = {};
          data.targetId = this.form2.targetId;
          data.contactActualNum = this.form2.contactActualNum;
          data.mobileActualNum = this.form2.mobileActualNum;
          data.visitActualNum = this.form2.visitActualNum;
          data.detailData = []
          this.form2.detailData.forEach((el)=>{
            let checkContent = el.checkContent
            if(el.trackingId){
              checkContent = el.trackingContent
            }
            data.detailData.push({
              trackingId:el.trackingId,
              detailId:el.detailId,
              customerId:el.customerId,
              checkContent:checkContent
            })
          })
          saleTargetCheck(data).then((res)=>{
            this.btnLoading2 = false;
            this.handleClose2();
            this.getList();
          }).catch(()=>{
            this.btnLoading2 = false;
          })
        }
      })
    },

    //关闭确认目标
    handleClose2(){
      this.dialogVisible2 = false;
    },

    //显示明细
    showPop3(item){
      this.dialogVisible3 = true;
      this.listQuery3 = JSON.parse(JSON.stringify(defaultListQuery2));
      this.listQuery3.targetId = item.targetId;
      this.listQuery3.tab = 'all'
      this.getList3()
    },
    getList3(){
      saleTargetDetailList(this.listQuery3).then((res)=>{
        this.tableData3 = this.farmtList(res.list)
        this.count3 = res.count
      })
    },
    handleSizeChange3(val){
      this.listQuery3.pageNum = 1;
      this.listQuery3.pageSize = val;
      this.getList3();
    },
    handleCurrentChange3(val){
      this.listQuery3.pageNum = val;
      this.getList3();
    },


    //获取客户列表
    remoteMethod(query) {
      if(query && query!= ''){
        getCustomerOption({keywords:query,chargeId:this.userId}).then(response => {
          this.customerList = response;
        }).catch(()=>{
        });
      }
    },

    //切换类型
    handleSelect(key){
      this.tab = key;
      this.listQuery = JSON.parse(JSON.stringify(defaultListQuery));
      this.listQuery2 = JSON.parse(JSON.stringify(defaultListQuery2));
      this.listQuery.targetDate = [this.startDate,this.endDate];
      this.listQuery2.targetDate = [this.startDate,this.endDate];
      this.handleSearchList()
      this.handleSearchList2()
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
      this.getChartsData();
    },

    //获取列表
    getList() {
      this.listLoading = true;
      let pa = JSON.parse(JSON.stringify(this.listQuery))
      pa.tab = this.tab
      saleTargetList(pa).then(response => {
        this.tableData = response.list;
        this.count = response.count;
        this.finishedRate = response.finishedRate
        this.saleActualAllNum = response.saleActualAllNum
        this.saleTargetAllNum = response.saleTargetAllNum
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },


    handleSizeChange2(val){
      this.listQuery2.pageNum = 1;
      this.listQuery2.pageSize = val;
      this.getList2();
    },
    handleCurrentChange2(val){
      this.listQuery2.pageNum = val;
      this.getList2();
    },

    handleSearchList2(){
      this.listQuery2.pageNum = 1;
      this.getList2();
    },
    farmtList(responseList){
      let  list = []
      responseList.forEach((el,i)=>{
        el.customerList.forEach((ee,ii)=>{
          list.push({
            targertId: el.targertId,
            detailId: el.detailId,
            targetDate: el.targetDate,
            userRealName: el.userRealName,
            departmentName: el.departmentName,
            goodsKingId:el.goodsKingId,
            goodsSn:el.goodsSn,
            goodsName:el.goodsName,
            saleTargetNum:el.saleTargetNum,
            saleActualNum:el.saleActualNum,
            isFinished:el.isFinished,
            targetState:el.targetState,
            checkTime:el.checkTime,
            customerId:ee.customerId,
            customerName:ee.customerName,
            inquiryCount:ee.inquiryCount,
            customerSaleActuaNum:ee.saleActualNum,
            orderList:ee.orderList,
            checkContent:ee.checkContent,
            trackingId:ee.trackingId,
            trackingContent:ee.trackingContent,
            isRowSpan:ii == 0 ? true :false,
            rowNum:el.customerList.length
          })
        })
      })
      return list
    },

    //获取列表
    getList2() {
      this.listLoading2 = true;
      let pa = JSON.parse(JSON.stringify(this.listQuery2))
      pa.tab = this.tab
      saleTargetDetailList(pa).then(response => {
        this.tableData2= this.farmtList(response.list)
        this.count2 = response.count;
        this.listLoading2 = false;
      }).catch(()=>{
        this.listLoading2 = false;
      });
    },
  },
}
</script>

<style scoped lang="scss">

</style>
